import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:file_picker/file_picker.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class BasePicker extends StatelessWidget {
  /// 选择图片
  final bool showImagePicker;

  /// 选择视频
  final bool showVideoPicker;

  /// 选择文件
  final bool showFilePicker;

  final BuildContext widgetContext;

  final Function(List<dynamic> assets) getPickerAssets;

  /// 拆分返回数据
  final bool splitPaths;

  final Function(BaseKeyValueModel typeModel) getPickerAssetsType;

  final int maxAssetsForAssetsForGallery;

  const BasePicker({Key key, @required this.widgetContext, @required this.showImagePicker, @required this.showVideoPicker, @required this.getPickerAssets, this.maxAssetsForAssetsForGallery = 9, this.getPickerAssetsType, this.showFilePicker = false, this.splitPaths = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<BaseKeyValueModel> items = this._getListViewDataSource();
    return Container(
      alignment: Alignment.center,
      height: double.parse((items.length * 55).toString()),
      child: _buildListViewWidget(items),
    );
  }

  Widget _buildListViewWidget(List<BaseKeyValueModel> items) {
    return ListView.separated(
      itemBuilder: (BuildContext itemContext, int index) {
        BaseKeyValueModel item = items[index];
        return _buildBottomSheetItem(item);
      },
      itemCount: items.length,
      separatorBuilder: (BuildContext context, int index) => BaseComponentUtils.buildHorizontalDivider(),
    );
  }

  List<BaseKeyValueModel> _getListViewDataSource() {
    List<BaseKeyValueModel> items = [];
    if (this.showImagePicker == true) {
      List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '0', value: '拍照')];
      items.addAll(picker);
    }
    if (this.showVideoPicker == true) {
      List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '1', value: '拍视频')];
      items.addAll(picker);
    }
    if (this.showImagePicker == true) {
      List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '2', value: '从相册中选择图片')];
      items.addAll(picker);
    }
    if (this.showVideoPicker == true) {
      List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '3', value: '从相册中选择视频')];
      items.addAll(picker);
    }

    if (this.showFilePicker == true) {
      List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '4', value: '选择文件')];
      items.addAll(picker);
    }

    List<BaseKeyValueModel> picker = [new BaseKeyValueModel(key: '5', value: '取消')];
    items.addAll(picker);
    return items;
  }

  Widget _buildBottomSheetItem(BaseKeyValueModel item) {
    return InkWell(
      onTap: () => this._onBottomSheetItemPress(item),
      child: Container(
        alignment: Alignment.center,
        height: 50.0,
        child: Text(item.value, style: TextStyle(fontSize: 14.0, color: BaseStyles.bodyMedium(this.widgetContext).color)),
      ),
    );
  }

  void _onBottomSheetItemPress(BaseKeyValueModel item) {
    switch (item.key) {
      case '0': // 拍照
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '0', value: '拍照'));
        this._getImageForCamera();
        break;
      case '1': // 拍视频
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '1', value: '拍视频'));
        this._getVideoForCamera();
        break;
      case '2': // 从相册中选择图片
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '2', value: '从相册中选择图片'));
        this._getAssetsForGallery(isShowVideo: false);
        break;
      case '3': // 从相册中选择视频
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '3', value: '从相册中选择视频'));
        this._getAssetsForGallery(isShowVideo: true);
        break;
      case '4': // 选择文件
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '4', value: '选择文件'));
        this._pickFiles();
        break;
      case '5': // 取消
        if (this.getPickerAssetsType != null) this.getPickerAssetsType(BaseKeyValueModel(key: '5', value: '取消'));
        Navigator.of(this.widgetContext).pop();
        break;
    }
  }

  /// 拍照
  void _getImageForCamera() async {
    PickedFile file = await ImagePicker().getImage(source: ImageSource.camera);
    if (file != null) {
      Navigator.of(this.widgetContext).pop();
      BaseComponentUtils.showLoadingDialog(this.widgetContext, hint: '正在上传');
      BaseHttpResultModel result = await dioUtil.fetchUploadFile(file.path);
      BaseComponentUtils.hideLoadingDialog(this.widgetContext);
      if (result.success == true) {
        String fileRealPath = BaseUtils.getKeyData(result.data, "fileRealPath").toString();
        List<dynamic> urls = ['$fileRealPath'];
        if (!this.splitPaths) this.getPickerAssets(urls);
        if (this.splitPaths) {
          String fileSource = BaseUtils.getKeyData(result.data, "fileSource").toString();
          String fileName = file.path.split('/').last;
          String extension = fileName.contains('.') ? fileName.split('.').last : '';
          Map<String, dynamic> item = {'fileName': fileName, 'extension': extension, 'path': file.path, 'fileSource': fileSource, 'fileRealPath': fileRealPath, 'fileUrl': '$fileSource' + fileRealPath};
          this.getPickerAssets([item]);
        }
      }
    }
  }

  /// 拍视频
  void _getVideoForCamera() async {
    PickedFile file = await ImagePicker().getVideo(source: ImageSource.camera);
    if (file != null) {
      Navigator.of(this.widgetContext).pop();
      BaseComponentUtils.showLoadingDialog(this.widgetContext, hint: '正在上传');
      BaseHttpResultModel result = await dioUtil.fetchUploadFile(file.path);
      BaseComponentUtils.hideLoadingDialog(this.widgetContext);
      if (result.success == true) {
        String fileRealPath = BaseUtils.getKeyData(result.data, "fileRealPath").toString();
        List<dynamic> urls = ['$fileRealPath'];
        if (!this.splitPaths) this.getPickerAssets(urls);
        if (this.splitPaths) {
          String fileSource = BaseUtils.getKeyData(result.data, "fileSource").toString();
          String fileName = file.path.split('/').last;
          String extension = fileName.contains('.') ? fileName.split('.').last : '';
          Map<String, dynamic> item = {'fileName': fileName, 'extension': extension, 'path': file.path, 'fileSource': fileSource, 'fileRealPath': fileRealPath, 'fileUrl': '$fileSource' + fileRealPath};
          this.getPickerAssets([item]);
        }
      }
    }
  }

  /// 从相册中选择视频或者图片
  void _getAssetsForGallery({@required bool isShowVideo}) async {
    RequestType requestType = this._getGalleryRequestType(isShowVideo: isShowVideo);
    List<AssetEntity> items = await AssetPicker.pickAssets(this.widgetContext, requestType: requestType, selectedAssets: [], themeColor: Colors.blue, maxAssets: this.maxAssetsForAssetsForGallery, pathThumbSize: 1000, gridCount: 4);
    if (items != null && items.length > 0) {
      Navigator.of(this.widgetContext).pop();
      List<AssetEntity> imageItems = items.where((element) => element.type == AssetType.image).toList();
      List<AssetEntity> videoItems = items.where((element) => element.type == AssetType.video).toList();
      List<dynamic> urls = [];
      if (imageItems.length > 0) {
        BaseComponentUtils.showLoadingDialog(this.widgetContext, hint: '正在上传图片');
        List<dynamic> imageUrls = await dioUtil.fetchBatchUploadFile(imageItems, relativePath: true, splitPaths: this.splitPaths);
        BaseComponentUtils.hideLoadingDialog(this.widgetContext);
        urls.addAll(imageUrls);
      }
      if (videoItems.length > 0) {
        BaseComponentUtils.showLoadingDialog(this.widgetContext, hint: '正在上传视频');
        List<dynamic> videoUrls = await dioUtil.fetchBatchUploadVideoFile(videoItems, relativePath: true, splitPaths: this.splitPaths);
        BaseComponentUtils.hideLoadingDialog(this.widgetContext);
        urls.addAll(videoUrls);
      }
      this.getPickerAssets(urls);
    }
  }

  /// 选择文件
  void _pickFiles() async {
    File filePicker = await FilePicker.getFile();
    if (filePicker != null) {
      Navigator.of(this.widgetContext).pop();
      BaseComponentUtils.showLoadingDialog(this.widgetContext, hint: '正在上传');
      BaseHttpResultModel uploadResult = await dioUtil.fetchUploadFile(filePicker.path);
      BaseComponentUtils.hideLoadingDialog(this.widgetContext);
      if (uploadResult.success == true) {
        String fileRealPath = BaseUtils.getKeyData(uploadResult.data, "fileRealPath").toString();
        String fileSource = BaseUtils.getKeyData(uploadResult.data, "fileSource").toString();
        String fileName = filePicker.path.split('/').last;
        String extension = fileName.contains('.') ? fileName.split('.').last : '';
        Map<String, dynamic> item = {'fileName': fileName, 'extension': extension, 'path': filePicker.path, 'fileUrl': fileSource + fileRealPath, 'fileRealPath': fileRealPath, 'fileSource': fileSource};
        List<dynamic> assets = [item];
        this.getPickerAssets(assets);
      }
    }
  }

  RequestType _getGalleryRequestType({@required bool isShowVideo}) {
    if (!isShowVideo) return RequestType.image;
    if (isShowVideo) return RequestType.video;
    return RequestType.all;
  }
}
